<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { 
  getAllMerchantCategories, 
  getRecommendedMerchants, 
  getMerchantsByCategory,
  searchMerchants,
  type Merchant,
  type MerchantCategory
} from '@/api/merchant'
import { Message } from '@arco-design/web-vue'
import { IconLocation } from '@arco-design/web-vue/es/icon'

const router = useRouter()
const loading = ref(false)
const searchKeyword = ref('')
const selectedCategory = ref<number | null>(null)
const merchants = ref<Merchant[]>([])
const categories = ref<MerchantCategory[]>([])

// 分页数据
const pagination = reactive({
  page: 0,
  size: 10,
  total: 0,
  totalPages: 0
})

// 初始化数据
onMounted(async () => {
  loading.value = true
  try {
    // 获取所有商家分类
    const categoriesRes = await getAllMerchantCategories()
    if (categoriesRes.code === 200 && categoriesRes.data) {
      categories.value = categoriesRes.data
      console.log('成功获取商家分类:', categories.value)
    } else {
      throw new Error(categoriesRes.message || '获取商家分类失败')
    }

    // 获取推荐商家列表
    const recommendedRes = await getRecommendedMerchants()
    if (recommendedRes.code === 200 && recommendedRes.data) {
      merchants.value = recommendedRes.data
      console.log('成功获取推荐商家:', merchants.value)
    } else {
      throw new Error(recommendedRes.message || '获取推荐商家失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    Message.error('加载数据失败，请稍后再试')
  } finally {
    loading.value = false
  }
})

// 选择分类
const handleCategorySelect = async (categoryId: number) => {
  loading.value = true
  selectedCategory.value = categoryId
  pagination.page = 0
  
  try {
    const result = await getMerchantsByCategory(categoryId, pagination.page, pagination.size)
    if (result.code === 200 && result.data) {
      merchants.value = result.data.content
      pagination.total = result.data.totalElements
      pagination.totalPages = result.data.totalPages
      console.log('成功获取分类商家:', merchants.value)
    } else {
      throw new Error(result.message || '获取分类商家失败')
    }
  } catch (error) {
    console.error('加载分类商家失败:', error)
    Message.error('加载分类商家失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 搜索商家
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    Message.warning('请输入搜索关键词')
    return
  }
  
  loading.value = true
  pagination.page = 0
  selectedCategory.value = null
  
  try {
    const result = await searchMerchants(searchKeyword.value, pagination.page, pagination.size)
    if (result.code === 200 && result.data) {
      merchants.value = result.data.content
      pagination.total = result.data.totalElements
      pagination.totalPages = result.data.totalPages
      console.log('成功搜索商家:', merchants.value)
    } else {
      throw new Error(result.message || '搜索商家失败')
    }
  } catch (error) {
    console.error('搜索商家失败:', error)
    Message.error('搜索商家失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = async () => {
  if (pagination.page >= pagination.totalPages - 1) return
  
  loading.value = true
  pagination.page += 1
  
  try {
    let result;
    if (selectedCategory.value) {
      result = await getMerchantsByCategory(selectedCategory.value, pagination.page, pagination.size)
      if (result.code === 200 && result.data) {
        merchants.value = [...merchants.value, ...result.data.content]
        pagination.total = result.data.totalElements
        pagination.totalPages = result.data.totalPages
      } else {
        throw new Error(result.message || '加载更多商家失败')
      }
    } else if (searchKeyword.value) {
      result = await searchMerchants(searchKeyword.value, pagination.page, pagination.size)
      if (result.code === 200 && result.data) {
        merchants.value = [...merchants.value, ...result.data.content]
        pagination.total = result.data.totalElements
        pagination.totalPages = result.data.totalPages
      } else {
        throw new Error(result.message || '加载更多商家失败')
      }
    } else {
      // 如果既没有选择分类也没有搜索，则加载推荐商家
      const recommendedRes = await getRecommendedMerchants()
      if (recommendedRes.code === 200 && recommendedRes.data) {
        // 添加到现有列表
        const newMerchants = recommendedRes.data.filter(
          newMerchant => !merchants.value.some(existingMerchant => existingMerchant.id === newMerchant.id)
        );
        merchants.value = [...merchants.value, ...newMerchants]
      } else {
        throw new Error(recommendedRes.message || '加载更多推荐商家失败')
      }
    }
  } catch (error) {
    console.error('加载更多商家失败:', error)
    Message.error('加载更多商家失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 前往商家详情页
const goToMerchant = (merchantId: number) => {
  router.push(`/merchant/${merchantId}`)
}

// 重置筛选
const resetFilters = async () => {
  searchKeyword.value = ''
  selectedCategory.value = null
  pagination.page = 0
  
  loading.value = true
  try {
    const recommendedData = await getRecommendedMerchants()
    if (recommendedData.code === 200 && recommendedData.data) {
      merchants.value = recommendedData.data
    } else {
      throw new Error(recommendedData.message || '重置数据失败')
    }
  } catch (error) {
    console.error('重置数据失败:', error)
    Message.error('重置数据失败，请稍后再试')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="home-container">
    <!-- 头部横幅 -->
    <div class="banner">
      <div class="banner-content">
        <h1>欢迎使用康赟点餐系统</h1>
        <p>美食随心选，足不出户享美味</p>
      </div>
    </div>
    
    <!-- 搜索栏 -->
    <div class="search-container">
      <div class="search-wrapper">
        <a-input
          v-model="searchKeyword"
          placeholder="搜索商家、美食..."
          class="search-input"
          allow-clear
        />
        <a-button type="primary" @click="handleSearch" class="search-button">
          搜索
        </a-button>
      </div>
    </div>

    <!-- 分类列表 -->
    <div class="category-container">
      <a-scrollbar style="height: 70px">
        <div class="category-list">
          <a-tag
            checkable
            :checked="selectedCategory === null"
            @click="resetFilters"
            size="large"
            class="category-tag"
          >
            全部
          </a-tag>
          <a-tag
            v-for="category in categories"
            :key="category.id"
            checkable
            :checked="selectedCategory === category.id"
            @click="handleCategorySelect(category.id)"
            size="large"
            class="category-tag"
          >
            {{ category.name }}
          </a-tag>
        </div>
      </a-scrollbar>
    </div>

    <!-- 商家列表 -->
    <a-spin :loading="loading" tip="加载中...">
      <div class="merchant-grid">
        <a-empty v-if="merchants.length === 0" description="暂无商家数据" />
        <div 
          v-for="merchant in merchants" 
          :key="merchant.id" 
          class="merchant-card card"
          @click="goToMerchant(merchant.id)"
        >
          <div class="merchant-image">
            <img :src="'https://ts1.tc.mm.bing.net/th/id/R-C.5af328d5d8eb5d270d47f2767b1a2eaf?rik=ZJ4hWcKrZi0r2Q&riu=http%3a%2f%2fwww.lanhesheji.com%2fuploadfile%2f2018%2f0509%2f20180509093736305.jpg&ehk=zmIP5yveMXYEVBAM3dah3bmgRxDLuHlwkoyl0zBvz7o%3d&risl=&pid=ImgRaw&r=0'" alt="商家图片" />
            <!-- 移除tags相关代码，因为商家类型中不存在tags属性 -->
          </div>
          <div class="merchant-content">
            <div class="merchant-header">
              <h3 class="merchant-name">{{ merchant.name }}</h3>
              <div class="merchant-rating">
                <a-rate :model-value="merchant.rating || 0" readonly allow-half size="small" />
                <span v-if="merchant.rating" class="rating-score">{{ merchant.rating }}分</span>
              </div>
            </div>
            <p class="merchant-description">{{ merchant.description }}</p>
            <div class="merchant-info">
              <p class="info-item">
                <i class="icon-clock"></i>
                <span>{{ merchant.businessHours || '暂无营业时间' }}</span>
              </p>
              <p class="info-item">
                <icon-location />
                <span>{{ merchant.address || '暂无地址信息' }}</span>
              </p>
              <div class="merchant-price-info">
                <span class="delivery-fee">配送费: ¥{{ merchant.deliveryFee || 0 }}</span>
                <span class="min-order">起送价: ¥{{ merchant.minOrderAmount || 0 }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载更多 -->
      <div class="load-more" v-if="merchants.length > 0 && pagination.page < pagination.totalPages - 1">
        <a-button type="outline" @click="loadMore" :loading="loading">加载更多</a-button>
      </div>
    </a-spin>
  </div>
</template>

<style scoped>
.home-container {
  padding: var(--spacing-md);
}

/* 头部横幅 */
.banner {
  height: 200px;
  background: linear-gradient(135deg, var(--primary-light), var(--primary-dark));
  border-radius: var(--border-radius-lg);
  margin-bottom: var(--spacing-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
  overflow: hidden;
  position: relative;
}

.banner::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('https://via.placeholder.com/1200x400') center/cover;
  opacity: 0.2;
}

.banner-content {
  position: relative;
  z-index: 1;
}

.banner-content h1 {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: var(--spacing-sm);
}

.banner-content p {
  font-size: 18px;
  opacity: 0.9;
}

/* 搜索栏 */
.search-container {
  margin-bottom: var(--spacing-lg);
}

.search-wrapper {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  box-shadow: var(--box-shadow-light);
  border-radius: var(--border-radius-md);
  overflow: hidden;
}

.search-input {
  flex: 1;
  border-radius: 0;
  border-right: none;
}

.search-button {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  height: 100%;
}

/* 分类列表 */
.category-container {
  margin-bottom: var(--spacing-lg);
  background-color: var(--bg-color-light);
  border-radius: var(--border-radius-md);
  padding: var(--spacing-md);
  box-shadow: var(--box-shadow-light);
}

.category-list {
  display: flex;
  gap: var(--spacing-sm);
  padding: var(--spacing-xs) 0;
}

.category-tag {
  cursor: pointer;
  transition: var(--transition-normal);
  font-size: 14px;
}

/* 商家列表 */
.merchant-grid {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-lg);
}

.merchant-card {
  overflow: hidden;
  cursor: pointer;
  width: calc(50% - var(--spacing-lg));
  margin-bottom: var(--spacing-md);
  display: flex;
  flex-direction: row;
}

.merchant-image {
  position: relative;
  width: 150px;
  min-width: 150px;
  height: 180px;
  overflow: hidden;
}

.merchant-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.merchant-card:hover .merchant-image img {
  transform: scale(1.05);
}

.merchant-tags {
  position: absolute;
  bottom: var(--spacing-sm);
  left: var(--spacing-sm);
  display: flex;
  gap: var(--spacing-xs);
}

.merchant-content {
  padding: var(--spacing-md);
  flex: 1;
  display: flex;
  flex-direction: column;
}

.merchant-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: var(--spacing-sm);
}

.merchant-name {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: var(--text-primary);
}

.merchant-rating {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.rating-score {
  font-size: 14px;
  color: var(--warning-color);
  font-weight: 500;
}

.merchant-description {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: var(--spacing-md);
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.merchant-info {
  margin-top: auto;
}

.info-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  margin-bottom: var(--spacing-xs);
  font-size: 14px;
  color: var(--text-secondary);
}

.info-item i {
  font-size: 16px;
  color: var(--primary-color);
}

.merchant-price-info {
  display: flex;
  justify-content: space-between;
  margin-top: var(--spacing-sm);
  font-size: 14px;
}

.delivery-fee {
  color: var(--text-secondary);
}

.min-order {
  color: var(--text-secondary);
}

/* 加载更多 */
.load-more {
  text-align: center;
  margin: var(--spacing-lg) 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .banner {
    height: 150px;
  }
  
  .banner-content h1 {
    font-size: 24px;
  }
  
  .banner-content p {
    font-size: 16px;
  }
  
  .merchant-card {
    width: 100%;
    flex-direction: column;
  }
  
  .merchant-image {
    width: 100%;
    min-width: 100%;
    height: 180px;
  }
}
</style>
